<template>
  <draggable-dialog
      :dialogVisible="dialogVisible"
      :title="'会议房间: ' + agoraConfig.channel"
      width="750px"
      @close="dialogVisible = false"
  >
    <div class="video-conference">
      <!-- 呼叫弹窗 -->
      <call-dialog
          :visible="showCallDialog"
          :caller-name="callerName"
          @accept="handleAcceptCall"
          @reject="handleRejectCall"
      />
      <!-- 会议内容 -->
      <template v-if="isInMeeting">
        <!-- 视频网格 -->
        <div class="video-grid">
          <el-row :gutter="10">
            <el-col
                :span="remoteUsers.length > 3 ? 8 : 12"
            >
              <div class="video-container" id="local-player">
                <div class="user-info">我</div>
              </div>
            </el-col>
            <el-col
                v-for="user in remoteUsers"
                :key="user.uid"
                :span="remoteUsers.length > 3 ? 8 : 12"
            >
              <div class="video-container" :id="`user-${user.uid}`">
                <div class="user-info">用户 {{ user.uid }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
    </div>
    <template #footer>
      <div class="control-bar" v-if="!showCallDialog">
        <el-row type="flex" justify="space-between" align="middle">
          <el-col :span="24">
            <div class="control-buttons">
              <el-tooltip content="麦克风" placement="top">
                <el-button
                    :type="isAudioEnabled ? 'primary' : 'info'"
                    circle
                    @click="toggleAudio"
                    :icon="isAudioEnabled ? 'el-icon-microphone' : 'el-icon-turn-off-microphone'"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="摄像头" placement="top">
                <el-button
                    :type="isVideoEnabled ? 'primary' : 'info'"
                    circle
                    @click="toggleVideo"
                    :icon="isVideoEnabled ? 'el-icon-video-camera' : 'el-icon-video-camera-solid'"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="退出会议" placement="top">
                <el-button
                    type="danger"
                    circle
                    @click="leaveChannel"
                    icon="el-icon-phone"
                ></el-button>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>
      </div>
    </template>
  </draggable-dialog>
</template>

<script>
import AgoraRTC from 'agora-rtc-sdk-ng'
import CallDialog from './CallDialog.vue'
import DraggableDialog from '@/components/DraggableDialog'
export default {
  name: 'VideoConference',
  components: {
    CallDialog,
    DraggableDialog
  },
  props: {
    callerName: {
      type: String,
      required: true,
      default: ''
    },
    agoraConfig: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: true,
      client: null,
      localAudioTrack: null,
      localVideoTrack: null,
      remoteUsers: [],
      isAudioEnabled: true,
      isVideoEnabled: true,
      showCallDialog: false,
      isInMeeting: false,
      ringTone: null
    }
  },
  async mounted() {
    this.showCallDialog = true
    this.playRingTone()
  },
  beforeDestroy() {
    this.stopRingTone()
    this.leaveChannel()
  },
  methods: {
    playRingTone() {
      this.ringTone = new Audio()
      // this.ringTone.src = require('@/assets/audio/ringtone.mp3')
      this.ringTone.loop = true
      this.ringTone.play().catch(error => {
        console.log('自动播放被阻止:', error)
      })
    },

    stopRingTone() {
      if (this.ringTone) {
        this.ringTone.pause()
        this.ringTone.currentTime = 0
      }
    },

    async handleAcceptCall() {
      this.stopRingTone()
      this.showCallDialog = false
      this.isInMeeting = true
      try {
        await this.initializeAgora()
        await this.joinChannel()
      } catch (error) {
        this.$message.error('初始化失败：' + error.message)
        this.isInMeeting = false
      }
    },

    handleRejectCall() {
      this.stopRingTone()
      this.showCallDialog = false
      this.$message({
        type: 'info',
        message: '您已拒绝加入会议'
      })
      this.$router.push('/')
    },

    async initializeAgora() {
      this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' })

      this.client.on('user-published', async (user, mediaType) => {
        await this.client.subscribe(user, mediaType)
        if (mediaType === 'video') {
          if (!this.remoteUsers.find(u => u.uid === user.uid)) {
            this.remoteUsers.push(user)
          }
          console.log(user, '用户');
          setTimeout(() => {
            user.videoTrack.play(`user-${user.uid}`)
          }, 100)
        }
        if (mediaType === 'audio') {
          user.audioTrack.play()
        }
      })

      this.client.on('user-left', async (user) => {
        this.remoteUsers = this.remoteUsers.filter(u => u.uid !== user.uid)
      })
    },

    async joinChannel() {
      try {
        const uid = await this.client.join(this.agoraConfig.appId, this.agoraConfig.channel, this.agoraConfig.token || null, this.agoraConfig.uid || null)
        this.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack()
        this.localVideoTrack = await AgoraRTC.createCameraVideoTrack()
        await this.client.publish([this.localAudioTrack, this.localVideoTrack])
        this.localVideoTrack.play('local-player')
        console.log('this.localVideoTrack.play',this.localVideoTrack.play);
        this.$message.success('成功加入会议')
      } catch (error) {
        this.$message.error('加入会议失败: ' + error.message)
        this.isInMeeting = false
      }
    },

    async leaveChannel() {
      if (this.localAudioTrack) {
        this.localAudioTrack.stop()
        this.localAudioTrack.close()
      }
      if (this.localVideoTrack) {
        this.localVideoTrack.stop()
        this.localVideoTrack.close()
      }
      await this.client.leave()
      this.remoteUsers = []
      this.isInMeeting = false
      this.dialogVisible = false
      this.$message.success('已退出会议')
    },

    async toggleAudio() {
      if (this.localAudioTrack) {
        this.isAudioEnabled = !this.isAudioEnabled
        this.localAudioTrack.setEnabled(this.isAudioEnabled)
      }
    },

    async toggleVideo() {
      if (this.localVideoTrack) {
        this.isVideoEnabled = !this.isVideoEnabled
        this.localVideoTrack.setEnabled(this.isVideoEnabled)
      }
    }
  }
}
</script>

<style scoped>
.video-conference {
  width: 750px;
  height: 500px;
  background: #1a1a1a;
  padding: 20px;
}

.control-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: rgba(0, 0, 0, 0.8);
  z-index: 100;
}

.control-buttons {
  text-align: center;
}

.control-buttons .el-button {
  margin: 0 10px;
}

.video-grid {
  padding: 20px;
  padding-bottom: 100px;
}

.video-container {
  width: 100%;
  height: 220px;
  background: #2c2c2c;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.user-info {
  position: absolute;
  bottom: 10px;
  left: 10px;
  color: white;
  z-index: 1;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px 10px;
  border-radius: 4px;
}

.meeting-info {
  color: white;
}

.meeting-title {
  font-size: 16px;
}
</style>
